$(document).ready(function() {
    // 检查登录状态
    const userId = localStorage.getItem('userId');
    const role = localStorage.getItem('role');
    
    if (!userId || role !== '0') {
        window.location.href = '../index.html';
        return;
    }

    // 加载商品列表
    loadProducts();

    // 退出登录
    $('#logout').click(function(e) {
        e.preventDefault();
        // 清除所有本地存储的数据
        localStorage.clear();
        // 跳转到登录页面
        window.location.href = '../index.html';
    });
});

function loadProducts() {
    $.ajax({
        url: '/api/commodity/list',
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const products = response.data;
                const container = $('#productContainer');
                container.empty();
                
                products.forEach(product => {
                    if (product.status === 1) { // 只显示上架的商品
                        container.append(`
                            <div class="product-card">
                                <div class="product-info">
                                    <h3>${product.commodityName}</h3>
                                    <div class="seller">商家: ${product.sellerName || '未知商家'}</div>
                                    <div class="price">¥${product.price.toFixed(2)}</div>
                                    <div class="stock">库存: ${product.stock}</div>
                                </div>
                                <div class="product-actions">
                                    <div class="quantity-control">
                                        <button onclick="updateQuantity(${product.commodityId}, -1)" 
                                                ${product.stock <= 0 ? 'disabled' : ''}>-</button>
                                        <input type="number" 
                                               id="quantity-${product.commodityId}" 
                                               value="1" 
                                               min="1" 
                                               max="${product.stock}"
                                               onchange="validateQuantity(${product.commodityId}, ${product.stock})"
                                               ${product.stock <= 0 ? 'disabled' : ''}>
                                        <button onclick="updateQuantity(${product.commodityId}, 1)"
                                                ${product.stock <= 0 ? 'disabled' : ''}>+</button>
                                    </div>
                                    <button class="add-to-cart-btn" 
                                            onclick="addToCart(${product.commodityId})"
                                            ${product.stock <= 0 ? 'disabled' : ''}>
                                        ${product.stock <= 0 ? '已售罄' : '加入购物车'}
                                    </button>
                                </div>
                            </div>
                        `);
                    }
                });
            }
        }
    });
}

// 更新商品数量
function updateQuantity(commodityId, change) {
    const input = $(`#quantity-${commodityId}`);
    let newValue = parseInt(input.val()) + change;
    const max = parseInt(input.attr('max'));
    
    if (newValue < 1) newValue = 1;
    if (newValue > max) newValue = max;
    
    input.val(newValue);
}

// 验证输入的数量
function validateQuantity(commodityId, maxStock) {
    const input = $(`#quantity-${commodityId}`);
    let value = parseInt(input.val());
    
    if (isNaN(value) || value < 1) {
        value = 1;
    } else if (value > maxStock) {
        value = maxStock;
    }
    
    input.val(value);
}

// 修改添加到购物车的函数
function addToCart(commodityId) {
    const userId = localStorage.getItem('userId');
    const quantity = parseInt($(`#quantity-${commodityId}`).val());
    
    $.ajax({
        url: '/api/cart/add',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            userId: parseInt(userId),
            commodityId: commodityId,
            amount: quantity
        }),
        success: function(response) {
            if (response.code === 200) {
                // 显示成功提示
                const message = $('<div>')
                    .addClass('message success')
                    .css({
                        'position': 'fixed',
                        'top': '20%',
                        'left': '50%',
                        'transform': 'translateX(-50%)',
                        'padding': '15px 30px',
                        'background-color': '#4CAF50',
                        'color': 'white',
                        'border-radius': '4px',
                        'z-index': 1000,
                        'box-shadow': '0 2px 5px rgba(0,0,0,0.2)',
                        'opacity': 0,
                        'display': 'flex',
                        'align-items': 'center',
                        'gap': '15px'
                    });

                // 添加成功文本
                message.append($('<span>').text(`成功添加${quantity}件商品到购物车！`));

                // 添加查看购物车链接
                const link = $('<a>')
                    .text('查看购物车')
                    .attr('href', 'cart.html')
                    .css({
                        'color': 'white',
                        'text-decoration': 'underline',
                        'font-weight': 'bold',
                        'cursor': 'pointer'
                    });

                message.append(link);
                $('body').append(message);
                message.animate({ opacity: 1 }, 300);

                // 3秒后消失
                setTimeout(() => {
                    message.animate({ opacity: 0 }, 300, function() {
                        $(this).remove();
                    });
                }, 2000);

                // 刷新商品列表以更新库存
                loadProducts();
            } else {
                alert(response.message || '添加失败，请重试');
            }
        },
        error: function() {
            alert('添加失败，请重试');
        }
    });
} 